package com.mz.ieann.aide.utils

import android.app.Activity
import android.app.Application
import android.os.Bundle
import android.os.StrictMode
import android.util.Log
import com.mz.ieann.aide.BuildConfig
import com.mz.ieann.dokit.utils.FileWrite
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale

/**
 * <p>------------------------------------------------------
 * <p>Copyright (C) 2020 wasu company, All rights reserved.
 * <p>------------------------------------------------------
 * <p> BaseApplication 中初始化
 * <p>
 *
 * @author Created by zhangmz
 * @date on 2023/7/4
 */
class AppUtil {

    /**
     * application启动前初始化
     */
    fun initApp(application: Application){
        if (BuildConfig.DEBUG){
//            initStrictMode()
        }
        Thread.setDefaultUncaughtExceptionHandler(appCrashHandler)
        application.registerActivityLifecycleCallbacks(activityLifecycleCallbacks)
    }

    fun onTerminate(application: Application){
        application.unregisterActivityLifecycleCallbacks(activityLifecycleCallbacks)
    }

    /**
     * StrictMode 开发这调优工具
     * https://developer.android.google.cn/reference/kotlin/android/os/StrictMode?hl=en
     */
    private fun initStrictMode(){
        StrictMode.setThreadPolicy(
            StrictMode.ThreadPolicy.Builder()
                .detectDiskReads()
                .detectDiskWrites()
                .detectNetwork() // or .detectAll() for all detectable problems
                .penaltyLog()
                .build()
        )

        StrictMode.setVmPolicy(
            StrictMode.VmPolicy.Builder()
                .detectLeakedSqlLiteObjects()
                .detectLeakedClosableObjects()
                .penaltyLog()
                .penaltyDeath()
                .build()
        )
    }

    /**
     * 全局捕获系统日志，保存在sd卡中
     */
    private val dateFormat = SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA)
    private val appCrashHandler = object : Thread.UncaughtExceptionHandler {
        override fun uncaughtException(t: Thread, e: Throwable) {
            runCatching {
                Log.e("crash", "Warning!!!, app occur crash.......", e)
                val sw = java.io.StringWriter()
                val pw = java.io.PrintWriter(sw)
                e.printStackTrace(pw)
                val date: String = dateFormat.format(Date())
                FileWrite.writeCards("crash_$date", "error:$e")
            }.onFailure {
                Log.e("crash", "catch app crash error:$it")
            }
        }
    }

    /**
     * 用来判断应用是在前台还是后台
     */
    private val activityLifecycleCallbacks: Application.ActivityLifecycleCallbacks =
        object : Application.ActivityLifecycleCallbacks {
            override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) {}
            override fun onActivityStarted(activity: Activity) {}
            override fun onActivityResumed(activity: Activity) {
            }
            override fun onActivityPaused(activity: Activity) {
            }
            override fun onActivityStopped(activity: Activity) {}
            override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) {}
            override fun onActivityDestroyed(activity: Activity) {
            }
        }
}